import { createStore, compose } from "redux";
import rootReducer from "./reducer";
// import { persistReducer, persistStore } from "redux-persist";
// import storage from "redux-persist/lib/storage";
// import { UserActionTypes } from "./user/types";

// 加载本地缓存的 state
const loadState = () => {
    try {
        const serializedState = localStorage.getItem("root-state");
        if (!serializedState) {
            // 一定要返回 undefined，这样 redux 才会重新加载初始化的 state
            return undefined;
        }
        return JSON.parse(serializedState);
    } catch (error) {
        console.log("redux state loading failure.");
        return undefined;
    }
};

// 为了调试 redux 程序，所以使用 compose 包装一个增强函数（就是 redux 的浏览器插件函数）
const composeEnhancer = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
    : compose();

const store =
    process.env.NODE_ENV === "development"
        ? createStore(rootReducer, loadState(), composeEnhancer())
        : createStore(rootReducer);

// 页面卸载前
window.onbeforeunload = () => {
    localStorage.setItem("root-state", JSON.stringify(store.getState()));
};

export default store;
